﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Commands.User.Commands.Order;
using DotNet.Common.Command;
using ZLCMS.Commands.User.Util;
using NHibernate;
using ZLCMS.Commands.Data;
using System.IO;
using Newtonsoft.Json;

namespace ZLCMS.Web.SystemManage.Basics.Shop.Order
{
    public partial class OrderList : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ分页控件
            _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);

            LoadOrderListParameter param = new LoadOrderListParameter();

            param.MemberPhone = string.IsNullOrEmpty(Request["phone"]) ? "" : Request["phone"];
            phone.Text = Request["phone"];

            param.ReceiverPhone = string.IsNullOrEmpty(Request["rcv_phone"]) ? "" : Request["rcv_phone"];
            rcv_phone.Text = Request["rcv_phone"];

            param.TradeNo = string.IsNullOrEmpty(Request["trade_no"]) ? "" : Request["trade_no"];
            trade_no.Text = Request["trade_no"];

            param.OrderNo = string.IsNullOrEmpty(Request["orderno"]) ? "" : Request["orderno"];
            orderno.Text = Request["orderno"];

            param.StartTime = string.IsNullOrEmpty(Request["start"]) ? "" : Request["start"];
            start.Text = Request["start"];

            param.EndTime = string.IsNullOrEmpty(Request["end"]) ? "" : Request["end"];
            end.Text = Request["end"];

            param.ConfirmedStatus = string.IsNullOrEmpty(Request["confirm"]) ? "-1" : Request["confirm"];
            ParamKit.Bind("OrderIsConfirmed", confirm, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, param.ConfirmedStatus, "-1");

            param.PayStatus = string.IsNullOrEmpty(Request["pay"]) ? "-1" : Request["pay"];
            ParamKit.Bind("OrderPayStatus", pay, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, param.PayStatus, "-1");

            param.ShippingStatus = string.IsNullOrEmpty(Request["shipping"]) ? "-1" : Request["shipping"];
            ParamKit.Bind("OrderShippingStatus", shipping, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, param.ShippingStatus, "-1");

            param.FinishedStatus = string.IsNullOrEmpty(Request["finish"]) ? "-1" : Request["finish"];
            ParamKit.Bind("OrderIsFinish", finish, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, param.FinishedStatus, "-1");

            param.CancelStatus = string.IsNullOrEmpty(Request["cancel"]) ? "-1" : Request["cancel"];
            ParamKit.Bind("OrderIsCancel", cancel, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, param.CancelStatus, "-1");


            param.UserAccount = UserKit.GetUserAccount();

            param.DeptCode = "";
            if (AuthUtil.CheckAuthorization("ORDER_MAN", "VIEW_ALL", param.UserAccount))
            {
            }
            else if (AuthUtil.CheckAuthorization("ORDER_MAN", "VIEW_OWNER", param.UserAccount))
            {
                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    param.DeptCode = session.CreateSQLQuery("select dept_code from sys_user_info where user_account=:acc")
                        .SetParameter("acc", param.UserAccount).UniqueResult<string>();
                }
            }
            else
            {
                //没有权限访问
                param.DeptCode = "no_dept";
            }


            if (!string.IsNullOrEmpty(Request["exportexcel"]))
            {
                //设置分页大小
                param.PageSize = 9999;
                //设置页码
                param.PageIndex = 1;

                ICommandResult<LoadOrderListResult> result = new LoadOrderListCommand().Execute(param);
                

                StringWriter sw = new StringWriter();

                sw.WriteLine("订单号\t快递单号\t快递代码\t支付金额\t收货人\t收货电话\t收货地址\t下单时间\t订单产品\t备注\t订单状态");
                foreach (OrderData item in result.Result.List)
                {
                    string productsStr = "";
                    foreach (var product in item.ProductList)
                    {
                        List<SKUGroup> skulist=JsonConvert.DeserializeObject<List<SKUGroup>>(product.SkuParamCode);
                        SKUGroup skuInfo = new SKUGroup();
                        if (skulist.Count>0)
                        {
                            skuInfo = skulist[0];
                        }

                        productsStr += product.ProductName + "[" + skuInfo.ItemName + "]" + "*" + product.Counter+",";
                    }

                    sw.WriteLine("'" + item.OrderNo + "\t'" + item.ShippingNo + "\t" + GetShippingCom(item.ShippingType) + "\t'" + string.Format("{0:F2}", item.PaymentPrice)
                        + "\t" + item.ReceiverName.Trim().Replace("\n", "") + "\t'" + item.ReceiverPhone.Trim().Replace("\n", "") 
                        + "\t" + item.ReceiverAddress.Trim().Replace("\n","")
                        + "\t" + item.OrderTime
                        + "\t" + productsStr
                        + "\t" + (string.IsNullOrEmpty(item.Remark.Trim()) ? "无" : item.Remark.Trim().Replace("\n", ""))
                        + "\t["+ ParamKit.GetValue("OrderIsConfirmed", item.CommentStatus, " ")
                        + "][" + ParamKit.GetValue("OrderPayStatus", item.PayStatus, " ")
                        + "][" + ParamKit.GetValue("OrderIsFinish", item.FinishedStatus, " ")
                        + "][" + ParamKit.GetValue("OrderIsCancel", item.CancelStatus, " ")
                        + "]\t");

                }
                sw.Close();

                OutputKit.OutputExcel(Response, sw);
            }
            else
            {
                //设置分页大小
                param.PageSize = _framePage.IsAjaxPagerPostBack ? _framePage.PageSize : 20;
                //设置页码
                param.PageIndex = _framePage.IsAjaxPagerPostBack ? _framePage.PageIndex : 1;

                ICommandResult<LoadOrderListResult> result = new LoadOrderListCommand().Execute(param);
                
                grid.DataSource = result.Result.List;
                grid.DataBind();
                _framePage.RecordCount = result.TotalCount;
            }

        }
        protected string GetShippingCom(string shippingType){
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                return session.CreateSQLQuery("select shipping_name from shop_shipping_info where type=:t")
                    .SetParameter("t", shippingType)
                    .UniqueResult<string>();
            }
        }

        protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("Products") as Repeater;//找到里层的repeater对象
                OrderData orderData = (OrderData)e.Item.DataItem;//找到分类Repeater关联的数据项 

                rep.DataSource = orderData.ProductList;
                rep.DataBind();
            }
        }
    }
}